package treeNode;

import java.util.*;

public class Solution9I {
    List<List<Integer>> ret = new LinkedList<List<Integer>>();
    Map<TreeNode, TreeNode> map = new HashMap<TreeNode, TreeNode>(); //存放 所有节点的父节点 key(子节点）->value（父节点）

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if (root == null) {
            return ret;
        }

        Queue<TreeNode> queueNode = new LinkedList<TreeNode>();  //存放 所有的节点
        Queue<Integer> queueSum = new LinkedList<Integer>();  // 节点的val
        queueNode.offer(root); //第一个节点 offer进去
        queueSum.offer(0); //

        while (!queueNode.isEmpty()) {
            TreeNode node = queueNode.poll();  //弹出第一个
            int rec = queueSum.poll() + node.val;

            if (node.left == null && node.right == null) {
                if (rec == sum) {
                    getPath(node);
                }
            } else {
                if (node.left != null) {
                    map.put(node.left, node);
                    queueNode.offer(node.left);
                    queueSum.offer(rec);
                }
                if (node.right != null) {
                    map.put(node.right, node);
                    queueNode.offer(node.right);
                    queueSum.offer(rec);
                }
            }
        }

        return ret;
    }

    public void getPath(TreeNode node) {
        List<Integer> temp = new LinkedList<Integer>();
        while (node != null) {
            temp.add(node.val);
            node = map.get(node);
        }
        Collections.reverse(temp);
        ret.add(new LinkedList<Integer>(temp));
    }

    public static void main(String[] args) {
//        TreeNode root = TreeNodeUtils.getTestTreeNode();
//        System.out.println(new Solution9I().pathSum(root,11));
        Queue<Integer> queue = new LinkedList<Integer>();
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        System.out.println(queue);
        while(!queue.isEmpty()){
            queue.poll();
            System.out.println("===="+queue);
        }

        System.out.println(queue);
    }

}
